import { Controller, Get, Post, Body, Patch, Param, Delete, Query, Inject, UnauthorizedException } from '@nestjs/common';
import { MailUserService } from './mail-user.service';
import { CreateMailUserDto } from './dto/create-mail-user.dto';
import { UpdateMailUserDto } from './dto/update-mail-user.dto';
import { LoginlUserDto } from './dto/login-user.dto'
import * as fs from 'fs';
import * as path from 'path';
import { RedisService } from '../redis/redis.service';
import { MailUser } from './entities/mail-user.entity';

@Controller('mail-user')
export class MailUserController {
  constructor(private readonly mailUserService: MailUserService) {}

  @Inject()
  private redisService: RedisService

  @Post('login')
  async login(@Body() loginUserDto: LoginlUserDto) {
    const {email, code} = loginUserDto
    const codeInRedis = await this.redisService.get(`captcha_${{email}}`)
    if(!codeInRedis) {
      throw new UnauthorizedException('验证码已失效');
    }
    if(code !== codeInRedis) {
      throw new UnauthorizedException('验证码不正确');
    }

    const user = await this.mailUserService.findUserByEmail(email)
    return  'success'
  }

  @Get('code')
  async sendEmail(@Query('address') address) {
    const code = Math.random().toString().slice(2, 8)
    await this.redisService.set(`captcha_${{address}}`, code, 5 * 60)
    await this.mailUserService.sendEmail({
      to: address,
      subject: '登录验证码',
      html: `<p>你的登录验证码是 ${code}</p>`
    });
    return '发送成功'
  }

  @Post()
  create(@Body() createMailUserDto: CreateMailUserDto) {
    return this.mailUserService.create(createMailUserDto);
  }

  @Get()
  findAll() {
    return this.mailUserService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.mailUserService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateMailUserDto: UpdateMailUserDto) {
    return this.mailUserService.update(+id, updateMailUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.mailUserService.remove(+id);
  }
}
